// 导入API请求
const { get, post } = require("../../utils/request");

Page({
  data: {
    activeTab: "unpaid", // 默认选项卡改为"待付款"
    orders: [], // 订单列表
    isLoading: false, // 是否正在加载
    hasMoreOrders: false, // 是否有更多订单
    pageNum: 1, // 当前页码
    pageSize: 10, // 每页数量
    courts: {}, // 缓存场地信息
  },

  onLoad: function () {
    // 获取所有场地信息，用于场地名称显示
    this.loadCourts();
    this.loadOrders();
  },

  onShow: function () {
    // 页面显示时刷新订单数据
    this.setData({
      pageNum: 1,
    });
    this.loadOrders();
  },

  // 获取所有场地信息
  loadCourts: function () {
    get("/court/list")
      .then((res) => {
        if (res.code === 200) {
          const courts = {};
          const courtList = res.data || [];
          // 将场地ID作为键，场地名称作为值存入对象中
          courtList.forEach((court) => {
            courts[court.id] = court.name;
          });
          this.setData({ courts });
        }
      })
      .catch((err) => {
        console.error("获取场地信息失败:", err);
      });
  },

  // 切换选项卡
  switchTab: function (e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      activeTab: type,
      orders: [],
      pageNum: 1,
    });
    this.loadOrders();
  },

  // 加载订单列表
  loadOrders: function () {
    const app = getApp();
    const loginStatus = app.checkLoginStatus();

    if (!loginStatus.isLoggedIn) {
      wx.showToast({
        title: "请先登录",
        icon: "none",
      });

      setTimeout(() => {
        wx.navigateTo({
          url: "/pages/registration/registration",
        });
      }, 1500);
      return;
    }

    const userId = loginStatus.userInfo.id;
    this.setData({ isLoading: true });

    // 使用修改后的/order/user/{userId}接口，可以接受查询参数
    let url = `/order/user/${userId}`;
    let params = {};

    // 根据选项卡类型添加不同的筛选参数
    switch (this.data.activeTab) {
      case "unpaid":
        params.payStatus = "unpaid";
        params.status = "normal"; // 只显示状态正常的订单
        break;
      case "paid":
        params.payStatus = "paid";
        break;
      case "unused":
        params.payStatus = "paid";
        params.status = "normal"; // 只显示状态正常且已支付的订单
        break;
      case "used":
        params.payStatus = "paid";
        params.status = "used"; // 添加：显示已使用的订单
        break;
    }

    get(url, params)
      .then((res) => {
        if (res.code === 200) {
          const orders = res.data || [];

          // 格式化订单数据
          const formattedOrders = orders.map((order) => {
            // 添加场地名称
            const courtName =
              this.data.courts[order.courtId] || `场地${order.courtId}`;

            // 提取日期和时间
            const startDate = this.formatDate(order.startTime);
            const startTimeStr = this.formatTime(order.startTime);
            const endTimeStr = this.formatTime(order.endTime);

            return {
              ...order,
              courtName: courtName, // 添加场地名称
              startDate: startDate, // 添加预约日期
              startTime: startTimeStr,
              endTime: endTimeStr,
              reserveTime: `${startDate} ${startTimeStr}-${endTimeStr}`, // 完整预约时间
              createTime: this.formatDateTime(new Date(order.createTime)),
            };
          });

          this.setData({
            orders: formattedOrders,
            isLoading: false,
          });
        } else {
          wx.showToast({
            title: res.message || "获取订单列表失败",
            icon: "none",
          });
          this.setData({ isLoading: false });
        }
      })
      .catch((err) => {
        console.error("获取订单失败:", err);
        wx.showToast({
          title: "获取订单失败，请稍后重试",
          icon: "none",
        });
        this.setData({ isLoading: false });
      });
  },

  // 加载更多订单
  loadMoreOrders: function () {
    // 待付款页签不支持加载更多，因为已经一次性加载了所有数据
    if (this.data.activeTab === "unpaid") {
      return;
    }

    this.setData({
      pageNum: this.data.pageNum + 1,
      isLoading: true,
    });

    const app = getApp();
    const loginStatus = app.checkLoginStatus();
    const userId = loginStatus.userInfo.id;

    let url = "/order/list";
    let params = {
      userId: userId,
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
    };

    // 根据不同选项卡添加不同的筛选条件
    if (this.data.activeTab === "paid") {
      params.payStatus = "paid";
    } else if (this.data.activeTab === "unused") {
      params.payStatus = "paid";
      params.status = "normal";
    } else if (this.data.activeTab === "used") {
      params.payStatus = "paid";
      params.status = "used";
    }

    get(url, params)
      .then((res) => {
        if (res.code === 200) {
          const newOrders = res.data.records || [];

          if (newOrders.length > 0) {
            // 格式化订单数据
            const formattedOrders = newOrders.map((order) => {
              return {
                ...order,
                startTime: this.formatTime(order.startTime),
                endTime: this.formatTime(order.endTime),
                createTime: this.formatDateTime(new Date(order.createTime)),
              };
            });

            // 追加新数据
            this.setData({
              orders: [...this.data.orders, ...formattedOrders],
              hasMoreOrders: newOrders.length >= this.data.pageSize,
              isLoading: false,
            });
          } else {
            this.setData({
              hasMoreOrders: false,
              isLoading: false,
            });
          }
        } else {
          wx.showToast({
            title: res.message || "加载更多订单失败",
            icon: "none",
          });
          this.setData({ isLoading: false });
        }
      })
      .catch((err) => {
        console.error("加载更多订单失败:", err);
        wx.showToast({
          title: "加载更多订单失败，请稍后重试",
          icon: "none",
        });
        this.setData({ isLoading: false });
      });
  },

  // 查看订单详情
  viewOrderDetail: function (e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/orderDetail/orderDetail?id=${orderId}`,
    });
  },

  // 取消订单
  cancelOrder: function (e) {
    const orderId = e.currentTarget.dataset.id;

    wx.showModal({
      title: "确认取消",
      content: "确定要取消该订单吗？",
      success: (res) => {
        if (res.confirm) {
          post("/order/cancel", null, {
            params: { id: orderId },
          })
            .then((res) => {
              if (res.code === 200) {
                wx.showToast({
                  title: "订单已取消",
                  icon: "success",
                });
                this.loadOrders(); // 刷新订单列表
              } else {
                wx.showToast({
                  title: res.message || "取消订单失败",
                  icon: "none",
                });
              }
            })
            .catch((err) => {
              console.error("取消订单失败:", err);
              wx.showToast({
                title: "取消订单失败，请稍后重试",
                icon: "none",
              });
            });
        }
      },
    });
  },

  // 支付订单
  payOrder: function (e) {
    const orderId = e.currentTarget.dataset.id;

    // 直接跳转到支付页面，只传递订单ID
    wx.navigateTo({
      url: `/pages/payment/payment?orderId=${orderId}`,
    });
  },

  // 使用订单
  useOrder: function (e) {
    const orderId = e.currentTarget.dataset.id;

    wx.showModal({
      title: "确认使用",
      content: "确认使用此预约？标记后将无法再次使用。",
      success: (res) => {
        if (res.confirm) {
          // 显示加载提示
          wx.showLoading({
            title: "处理中...",
            mask: true,
          });

          console.log("orderId", { id: Number(orderId) });

          // 调用标记为已使用接口
          get("/order/mark-used", { id: Number(orderId) })
            .then((res) => {
              wx.hideLoading();
              if (res.code === 200) {
                wx.showToast({
                  title: "标记使用成功",
                  icon: "success",
                });

                // 切换到已使用标签页
                this.setData({
                  activeTab: "used",
                  orders: [],
                  pageNum: 1,
                });
                this.loadOrders();
              } else {
                wx.showToast({
                  title: res.message || "操作失败",
                  icon: "none",
                });
              }
            })
            .catch((err) => {
              wx.hideLoading();
              console.error("使用订单失败:", err);
              wx.showToast({
                title: "操作失败，请稍后重试",
                icon: "none",
              });
            });
        }
      },
    });
  },

  // 前往预约页面
  goToReservation: function () {
    wx.switchTab({
      url: "/pages/venueReservation/venueReversation",
    });
  },

  // 格式化日期 YYYY-MM-DD
  formatDate: function (dateTimeStr) {
    if (!dateTimeStr) return "";
    const date = new Date(dateTimeStr);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");
    return `${year}-${month}-${day}`;
  },

  // 格式化时间 HH:MM
  formatTime: function (dateTimeStr) {
    if (!dateTimeStr) return "";
    const date = new Date(dateTimeStr);
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    return `${hours}:${minutes}`;
  },

  // 格式化日期时间为 YYYY-MM-DD HH:MM
  formatDateTime: function (date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");

    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },

  // 仅格式化日期 YYYY-MM-DD
  formatDateOnly: function (date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");

    return `${year}-${month}-${day}`;
  },
});
